﻿using Naruto.TaskManagement.Entitys.DTO;
using Naruto.TaskManagement.Entitys.Models;
using Naruto.TaskManagement.Entitys.VM;
using Naruto.TaskManagement.Infrastructure;
using Naruto.TaskManagement.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Naruto.TaskManagement.Application
{
    public class ChatSessionStateApps : IApp
    {
        private readonly IChatSessionStateRepository chatSessionStateRepository;

        private readonly IUserRepository userRepository;

        private readonly ITaskManageUnitOfWork unitOfWork;

        public ChatSessionStateApps(IChatSessionStateRepository _chatSessionStateRepository, ITaskManageUnitOfWork _unitOfWork, IUserRepository _userRepository)
        {
            chatSessionStateRepository = _chatSessionStateRepository;
            unitOfWork = _unitOfWork;
            userRepository = _userRepository;
        }


        /// <summary>
        /// 更新会话信息
        /// </summary>
        public async Task Update(UpdateChatSessionStateDTO info)
        {
            if (info == null || info.UserId.IsNullEmpty() || info.ReciveUserId.IsNullEmpty())
            {
                return;
            }
            //对象转换
            var sessionStateInfo = ExpressionMapper<UpdateChatSessionStateDTO, ChatSessionState>.To(info);

            //更新发起人
            await UpdateChat(sessionStateInfo);
            //更新接收人
            await UpdateChat(new ChatSessionState
            {
                ChatContent = info.ChatContent,
                ReciveUserId = info.UserId,
                UserId = info.ReciveUserId,
                ContentType = info.ContentType,
                ChatContentSendUserId = info.ChatContentSendUserId,
            });

            await unitOfWork.SaveChangeAsync();
        }

        private async Task UpdateChat(ChatSessionState info)
        {
            //获取发起人的会话状态id
            var sendUserChatSessionId = await chatSessionStateRepository.GetId(info.UserId, info.ReciveUserId);

            info.IsDelete = false;

            info.UpdateTime = DateTime.Now;

            info.Id = sendUserChatSessionId;
            //验证id是否存在
            if (sendUserChatSessionId.IsNullEmpty())
            {
                info.Id = SnowFlakeHelper.NewID();
                //添加会话信息
                await chatSessionStateRepository.Add(info);
            }
            else
            {
                await chatSessionStateRepository.Update(info);
            }
        }

        public async Task<NarutoResult> GetListByUserId(string userId)
        {
            if (userId.IsNullEmpty())
            {
                return new NarutoFailResult("参数错误");
            }
            //获取我的会话信息 
            var res = await chatSessionStateRepository.GetListByUserId(userId);

            var result = ExpressionMapper<GetListByUserIdViewModel, GetListByUserIdResultViewModel>.ToList(res);
            if (result != null && result.Count() > 0)
            {
                //遍历获取接收人的头像信息
                var heardImageUrlList = await userRepository.GetHeardImgUrlNameByUserIdList(result.Select(a => a.ReciveUserId).ToList());
                if (heardImageUrlList != null && heardImageUrlList.Count() > 0)
                {
                    result.ForEach(item =>
                    {
                        var heardImgUrlNameInfo = heardImageUrlList.Where(a => a.Id == item.ReciveUserId).FirstOrDefault();
                        if (heardImgUrlNameInfo != null)
                        {
                            item.HeardImgUrl = heardImgUrlNameInfo.HeardImgUrl;
                            item.Name = heardImgUrlNameInfo.Name;
                        }
                    });
                }
            }

            return new NarutoSuccessResult("操作成功", result);
        }

        /// <summary>
        /// 根据id删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<NarutoResult> DeleteById(string id)
        {
            await chatSessionStateRepository.DeleteById(id);
            await unitOfWork.SaveChangeAsync();
            return new NarutoSuccessResult("操作成功");
        }
    }
}
